import type { FormPathPattern } from '@formily/core/esm/types'
import { onFormInit } from '@formily/core'
import { getDicts } from '@/api/system/dict/data'
import useDictStore from '@/store/modules/dict'

export default function (path: FormPathPattern, dictType: string) {
  onFormInit(async (form) => {
    let dicts = useDictStore().getDict(dictType)
    if (!dicts) {
      const { data } = await getDicts(dictType)
      const value = data.map(p => ({ label: p.dictLabel, value: p.dictValue, elTagType: p.listClass, elTagClass: p.cssClass }))
      useDictStore().setDict(dictType, value)
      dicts = value
    }
    form.setFieldState(path, (state) => {
      state.loading = true
      state.dataSource = dicts!
      state.loading = false
    })
  })
}
